package com.jsyl.lwbk.web.controller.education;

import com.github.pagehelper.Page;
import com.jsyl.lwbk.business.domain.Child;
import com.jsyl.lwbk.business.domain.education.ChildTrainingProgram;
import com.jsyl.lwbk.business.domain.education.TrainingProgramChildRecord;
import com.jsyl.lwbk.business.dto.education.*;
import com.jsyl.lwbk.business.service.IChildService;
import com.jsyl.lwbk.business.service.education.IChildCourseService;
import com.jsyl.lwbk.business.service.education.IChildTrainingProgramService;
import com.jsyl.lwbk.business.service.education.ITrainingProgramChildRecordService;
import com.jsyl.lwbk.business.vo.education.ChildCourseVO;
import com.jsyl.lwbk.common.annotation.Log;
import com.jsyl.lwbk.common.constant.Constants;
import com.jsyl.lwbk.common.core.controller.BaseController;
import com.jsyl.lwbk.common.core.domain.AjaxResult;
import com.jsyl.lwbk.common.core.page.TableDataInfo;
import com.jsyl.lwbk.common.enums.BusinessType;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.DateUtils;
import com.jsyl.lwbk.common.utils.StringUtils;
import com.jsyl.lwbk.framework.util.ShiroUtils;
import com.jsyl.lwbk.system.domain.SysRole;
import com.jsyl.lwbk.system.utils.DictUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/education/schedule")
public class ChildScheduleController extends BaseController {

    @Autowired
    private IChildCourseService childCourseService;

    @Autowired
    private IChildService childService;

    @Autowired
    private IChildTrainingProgramService iChildTrainingProgramService;

    @Autowired
    private ITrainingProgramChildRecordService iTrainingProgramChildRecordService;



    private String prefix = "education/schedule";

    @RequiresPermissions("education:schedule:view")
    @GetMapping()
    public String childSchedule(ModelMap mmap) {
        mmap.put("teacherId", ShiroUtils.getUserId());
        return prefix + "/schedule";

    }

    @PostMapping("/listByTeacherIdAndMonth")
    @ResponseBody
    public TableDataInfo listByTeacherIdAndMonth(CourseChildListDTO courseChildListDTO) {
        boolean isTeacher =checkTeacher();
        if(!isTeacher){
            courseChildListDTO.setTeacherId(null);
        }
        startPage();
        List<ChildCourseVO> list = childCourseService.listByTeacherIdAndMonth(courseChildListDTO);
        return getDataTable(list);
    }

    private boolean checkTeacher(){
        List<SysRole> sysRoles = ShiroUtils.getSysUser().getRoles();
        if(CollectionUtils.isEmpty(sysRoles)){
            throw new BusinessException("无权限");
        }
        List<String> roleKeys = new ArrayList<String>();
        for(SysRole sysRole:sysRoles){
            roleKeys.add(sysRole.getRoleKey());
        }
        if(roleKeys.contains(Constants.ROLE_SUPERADMIN)){
            return false;
        }
//        if(!roleKeys.contains(Constants.ROLE_NORMALADMIN) && !roleKeys.contains(Constants.ROLE_TEACHERCHIEF) && !roleKeys.contains(Constants.ROLE_TEACHER) && !roleKeys.contains(Constants.ROLE_TEACHINGRESEARCH)){
//            throw new BusinessException("无权限");
//        }
        boolean isTeacher =false;
        if(roleKeys.contains(Constants.ROLE_TEACHER) &&roleKeys.size()==1){
            isTeacher = true;
        }
        return isTeacher;
    }



    @PostMapping("/listReportChildren")
    @ResponseBody
    public TableDataInfo listReportChildren(CourseChildListDTO courseChildListDTO) {
        boolean isTeacher =checkTeacher();
        if(!isTeacher){
            courseChildListDTO.setTeacherId(null);
        }
        else{
            courseChildListDTO.setTeacherId(ShiroUtils.getUserId());
        }
        Page page = startPage();
        List<ChildCourseVO> list = childCourseService.listReportChildren(courseChildListDTO);
        return getDataTable(list,page);
    }

    @GetMapping("/edit/{childId}/{projectType}/{scheduleTime}")
    @RequiresPermissions("education:schedule:edit")
    public String edit(@PathVariable("childId") Long childId,
                       @PathVariable("projectType") Integer projectType,
                       @PathVariable("scheduleTime") String scheduleTime, ModelMap mmap) {
        mmap.put("childId",childId);
        mmap.put("projectType",projectType);
        mmap.put("scheduleTime",scheduleTime);
        if(!StringUtils.isEmpty(scheduleTime)){
            mmap.put("monthTime", scheduleTime.split("-")[1] + "月");
        }
        Child child = childService.findById(childId);
        if(child != null){
            mmap.put("childName",child.getName());
            if(!StringUtils.isEmpty(child.getBirthYear())){
                Integer birthYear = Integer.parseInt(child.getBirthYear());
                int curYear = DateUtils.getYear(new Date());
                mmap.put("childAge",(curYear-birthYear)+"周岁");
            }

        }
        return prefix + "/edit";
    }
    @GetMapping("/newProgramEdit/{childId}/{projectType}/{scheduleTime}/{isNewProgram}")
    @RequiresPermissions("education:schedule:edit")
    public String newProgramEdit(@PathVariable("childId") Long childId,
                       @PathVariable("projectType") Integer projectType,
                       @PathVariable("scheduleTime") String scheduleTime,
                       @PathVariable("isNewProgram") Integer isNewProgram,ModelMap mmap) {
        mmap.put("childId",childId);
        mmap.put("projectType",projectType);
        mmap.put("scheduleTime",scheduleTime);
        mmap.put("isNewProgram",isNewProgram);
        if(!StringUtils.isEmpty(scheduleTime)){
            mmap.put("monthTime", scheduleTime.split("-")[1] + "月");
        }
        Child child = childService.findById(childId);
        if(child != null){
            mmap.put("childName",child.getName());
            if(!StringUtils.isEmpty(child.getBirthYear())){
                Integer birthYear = Integer.parseInt(child.getBirthYear());
                int curYear = DateUtils.getYear(new Date());
                mmap.put("childAge",(curYear-birthYear)+"周岁");
            }

        }
        return prefix + "/newProgramEdit";
    }

    /**
     * 查询教研设置标准
     * @param id
     * @param map
     * @return
     */
    @GetMapping("/editTraining/{id}")
    public String editTraining(@PathVariable("id") Long id, ModelMap map) {
        map.put("id",id);
        ChildTrainingProgram childTrainingProgram = iChildTrainingProgramService.findById(id);
        if(childTrainingProgram != null) {
            if(childTrainingProgram.getModifyContent()!=null) {
                String modifyContent = childTrainingProgram.getModifyContent();
               /* if(StringUtils.isEmpty(childTrainingProgram.getModifyTrainingContent())){
                    modifyContent = childTrainingProgram.getModifyContent();
                }
                else {
                    modifyContent = childTrainingProgram.getModifyTrainingContent();
                }*/
                map.put("modifyContent", childTrainingProgram.getModifyContent());
                map.put("modifyValue", modifyContent.substring(modifyContent.indexOf("[")+1,modifyContent.indexOf("]")));
            }
            map.put("modifyDirection", childTrainingProgram.getModifyDirection());
        }
        return prefix + "/editTraining";
    }


    /**
     * 修改老师设置标准
     * @param editTrainingProgramDTO
     * @return
     */
    @PostMapping("/editProgram")
    @ResponseBody
    public AjaxResult editSchedule(EditTrainingProgramDTO editTrainingProgramDTO) {
        if(editTrainingProgramDTO.getId() == null || StringUtils.isEmpty(editTrainingProgramDTO.getAfterModify())){
           return AjaxResult.success();
        }
        iChildTrainingProgramService.updateChildTrainingProgram(editTrainingProgramDTO);
        return AjaxResult.success();
    }

    /**
     * 替换项目
     * @param editTrainingProgramDTO
     * @return
     */
    @PostMapping("/saveReplaceProgram")
    @ResponseBody
    public AjaxResult saveReplaceProgram(EditTrainingProgramDTO editTrainingProgramDTO) {
        iChildTrainingProgramService.replaceChildTrainingProgram(editTrainingProgramDTO);
        return AjaxResult.success();
    }
    /**
     * 撤销替换项目
     * @param editTrainingProgramDTO
     * @return
     */
    @PostMapping("/saveRevokeProgram")
    @ResponseBody
    public AjaxResult saveRevokeProgram(EditTrainingProgramDTO editTrainingProgramDTO) {
        iChildTrainingProgramService.revokeChildTrainingProgram(editTrainingProgramDTO);
        return AjaxResult.success();
    }


     /**
     * 添加巩固项目
     * @param childId
     * @param map
     * @return
     */
    @GetMapping("/addConsolidate/{childId}/{projectType}/{scheduleTime}")
    public String addConsolidate(@PathVariable("childId")Long childId, @PathVariable("projectType") Integer projectType,@PathVariable("scheduleTime")String scheduleTime, ModelMap map) {
        map.put("childId", childId);
        map.put("projectType", projectType);
        map.put("scheduleTime", scheduleTime);
        return prefix + "/addConsolidate";
    }

    /**
     *
     * @param programId
     * @param map
     * @return
     */
    @GetMapping("/replaceTrainingProgram/{programId}")
    public String addConsolidate(@PathVariable("programId")Long programId,ModelMap map) {
        map.put("programId", programId);
        return prefix + "/replaceTrainingProgram";
    }

    @PostMapping("/listReplaceTrainingProgram")
    @ResponseBody
    public TableDataInfo listReplaceTrainingProgram(TrainingProgramChildRecordListDTO dto) {
        if(dto.getTrainingContent()==null || dto.getTrainingContent() ==""||dto.getTrainingContent().length()<2){
            return getDataTable(new ArrayList<ChildTrainingProgram>());
        }
        List<ChildTrainingProgram> childTrainingPrograms=iChildTrainingProgramService.listReplaceTrainingProgram(dto.getProgramId(),dto.getTrainingContent());
        return getDataTable(childTrainingPrograms);
    }
    @PostMapping("/listConsolidate")
    @ResponseBody
    public TableDataInfo listConsolidate(TrainingProgramChildRecordListDTO dto) {
//        trainingProgramChildRecordListDTO.setTrainingProgramNumber(DateUtils.getDateYYYYMM());
//        trainingProgramChildRecordListDTO.setTrainingLevel(2);
//        trainingProgramChildRecordListDTO.setChildId(trainingProgramChildRecordListDTO.getChildId());
//        trainingProgramChildRecordListDTO.setProjectType(trainingProgramChildRecordListDTO.getProjectType());
//        List<TrainingProgramChildRecord> list = iTrainingProgramChildRecordService.list(trainingProgramChildRecordListDTO);
//        //查找对应的训练项目
//        List<ChildTrainingProgram> childTrainingPrograms = new ArrayList<ChildTrainingProgram>();
//        if(!CollectionUtils.isEmpty(list)){
//            //去除重复的训练项目
//            list = removeDuplicate(list);
//            for(TrainingProgramChildRecord trainingProgramChildRecord:list) {
//                ChildTrainingProgram childTrainingProgram = iChildTrainingProgramService.findById(trainingProgramChildRecord.getChildTrainingProgramId());
//                if(childTrainingProgram != null) {
//                    childTrainingPrograms.add(childTrainingProgram);
//                }
//            }
//        }
        List<ChildTrainingProgram> childTrainingPrograms=iChildTrainingProgramService.listLastConsolidates(dto);
        return getDataTable(childTrainingPrograms);
    }

    private  List<TrainingProgramChildRecord>  removeDuplicate(List<TrainingProgramChildRecord> list)  {
        List<TrainingProgramChildRecord> tem  = new ArrayList<TrainingProgramChildRecord>();
        tem.addAll(list);
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).getChildTrainingProgramId().equals(list.get(i).getChildTrainingProgramId()))  {
                    TrainingProgramChildRecord trainingProgramChildRecord =  list.get(j);
                    tem.remove(trainingProgramChildRecord);
                }
            }
        }
        return tem;
    }
    /**
     * 保存训练项目
     */
    @Log(title = "保存训练项目", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult add(@Valid @RequestBody SaveChildTrainingProgramDTO saveChildTrainingProgramDTO) {
        iChildTrainingProgramService.saveChildTrainingProgram(saveChildTrainingProgramDTO,ShiroUtils.getSysUser().getNameCn());
        return toAjax(Boolean.TRUE);
    }

    /**
     * 保存标准训练项目
     */
    @Log(title = "保存训练项目", businessType = BusinessType.INSERT)
    @PostMapping("/saveNewProgram")
    @ResponseBody
    public AjaxResult saveNewProgram(@Valid @RequestBody SaveChildTrainingProgramDTO saveChildTrainingProgramDTO) {
        iChildTrainingProgramService.saveNewChildTrainingProgram(saveChildTrainingProgramDTO,ShiroUtils.getSysUser().getNameCn());
        return toAjax(Boolean.TRUE);
    }

    /**
     * 查询待巩固
     */
    @PostMapping("/listConsolidates")
    @ResponseBody
    public AjaxResult listConsolidates(@Valid @RequestBody ListConsolidatesDTO listConsolidatesDTO) {
        List<ChildTrainingProgram> childTrainingPrograms = iChildTrainingProgramService.listConsolidates(listConsolidatesDTO);
        return AjaxResult.success(childTrainingPrograms);
    }

    @GetMapping("/checkProgram/{childId}/{projectType}/{scheduleTime}/{teacherName}/{isNewProgram}")
    public String checkProgram(@PathVariable("childId") Long childId,
                               @PathVariable("projectType") Integer projectType,
                               @PathVariable("scheduleTime") String scheduleTime,
                               @PathVariable("teacherName") String teacherName,
                               @PathVariable(value = "isNewProgram") Integer isNewProgram,ModelMap mmap) {
        mmap.put("childId",childId);
        mmap.put("projectType",projectType);
        mmap.put("projectName", DictUtils.getDictLabel("business_project_type",projectType+""));
        mmap.put("scheduleTime",scheduleTime);
        mmap.put("teacherName",teacherName);
        mmap.put("isNewProgram",isNewProgram);
        if(!StringUtils.isEmpty(scheduleTime)){
            mmap.put("monthTime", scheduleTime.split("-")[1] + "月");
        }
        Child child = childService.findById(childId);
        if(child != null){
            mmap.put("childName",child.getName());
            if(!StringUtils.isEmpty(child.getBirthYear())){
                Integer birthYear = Integer.parseInt(child.getBirthYear());
                int curYear = DateUtils.getYear(new Date());
                mmap.put("childAge",(curYear-birthYear)+"周岁");
            }

        }
        return prefix + "/checkProgram";
    }



    @GetMapping("/downloadTrainingProgramTeacher/{childId}/{projectType}/{scheduleTime}/{teacherName}/{centerId}/{isNewProgram}")
    @ResponseBody
    public AjaxResult downloadTrainingProgramTeacher(@PathVariable("childId") Long childId,
                                                     @PathVariable("projectType") Integer projectType,
                                                     @PathVariable("scheduleTime") String scheduleTime,
                                                     @PathVariable("teacherName") String teacherName,
                                                     @PathVariable("centerId") Long centerId,
                                                     @PathVariable("isNewProgram") Integer isNewProgram, ModelMap mmap) {
        ListConsolidatesDTO listConsolidatesDTO  = new ListConsolidatesDTO();
        listConsolidatesDTO.setCenterId(centerId);
        listConsolidatesDTO.setChildId(childId);
        listConsolidatesDTO.setProjectType(projectType);
        listConsolidatesDTO.setScheduleTime(scheduleTime);
        listConsolidatesDTO.setIsNewProgram(isNewProgram);
        CheckProgramDTO checkProgramDTO = iChildTrainingProgramService.getCheckProgramDTO(listConsolidatesDTO);
        if(checkProgramDTO == null && CollectionUtils.isEmpty(checkProgramDTO.getChildTrainingPrograms())){
            throw new BusinessException("未生成训练项目");
        }
        checkProgramDTO.setProjectName(DictUtils.getDictLabel("business_project_type",projectType+""));
        if(!StringUtils.isEmpty(scheduleTime)){
            checkProgramDTO.setMonthTime(scheduleTime.split("-")[0]+"年"+scheduleTime.split("-")[1] + "月");
        }
        Child child = childService.findById(childId);
        if(child != null){
            checkProgramDTO.setChildName(child.getName());
            if(!StringUtils.isEmpty(child.getBirthYear())){
                Integer birthYear = Integer.parseInt(child.getBirthYear());
                int curYear = DateUtils.getYear(new Date());
                checkProgramDTO.setChildage((curYear-birthYear)+"周岁");
            }
        }
        checkProgramDTO.setChildId(childId);
        checkProgramDTO.setScheduleTime(scheduleTime);
        checkProgramDTO.setTeacherName(checkProgramDTO.getChildTrainingPrograms().get(0).getUpdateBy());
        String url = iChildTrainingProgramService.downloadTrainingProgramTeacher(listConsolidatesDTO,checkProgramDTO,1,ShiroUtils.getLoginName());
        return AjaxResult.success(url);
    }


    @GetMapping("/downloadDataRecordTeacher/{childId}/{projectType}/{scheduleTime}/{teacherName}/{centerId}")
    @ResponseBody
    public AjaxResult downloadDataRecordTeacher(@PathVariable("childId") Long childId, @PathVariable("projectType") Integer projectType, @PathVariable("scheduleTime") String scheduleTime, @PathVariable("teacherName") String teacherName,@PathVariable("centerId") Long centerId,ModelMap mmap) {
        ListConsolidatesDTO listConsolidatesDTO  = new ListConsolidatesDTO();
        listConsolidatesDTO.setCenterId(centerId);
        listConsolidatesDTO.setChildId(childId);
        listConsolidatesDTO.setProjectType(projectType);
        listConsolidatesDTO.setScheduleTime(scheduleTime);
        listConsolidatesDTO.setTeacherName(teacherName);
        CheckProgramDTO checkProgramDTO = iChildTrainingProgramService.getCheckProgramDTO(listConsolidatesDTO);
        if(checkProgramDTO == null && CollectionUtils.isEmpty(checkProgramDTO.getChildTrainingPrograms())){
            throw new BusinessException("未生成训练项目");
        }
        checkProgramDTO.setProjectName(DictUtils.getDictLabel("business_project_type",projectType+""));
        Child child = childService.findById(childId);
        if(child != null){
            checkProgramDTO.setChildName(child.getName());
            if(!StringUtils.isEmpty(child.getBirthYear())){
                Integer birthYear = Integer.parseInt(child.getBirthYear());
                int curYear = DateUtils.getYear(new Date());
                checkProgramDTO.setChildage((curYear-birthYear)+"周岁");
            }
        }
        checkProgramDTO.setTeacherName(checkProgramDTO.getChildTrainingPrograms().get(0).getUpdateBy());
        checkProgramDTO.setChildId(childId);
        checkProgramDTO.setScheduleTime(scheduleTime);
        String url = iChildTrainingProgramService.downloadTrainingProgramTeacher(listConsolidatesDTO,checkProgramDTO,2,ShiroUtils.getLoginName());
        return AjaxResult.success(url);
    }


    @PostMapping("/downloadTrainingReport")
    @ResponseBody
    public AjaxResult downloadTrainingReport(TrainingProgramChildRecordListDTO trainingProgramChildRecordListDTO) {
        TrainingReportDTO trainingReportDTO = iTrainingProgramChildRecordService.findTrainingReport(trainingProgramChildRecordListDTO);
        String url = iChildTrainingProgramService.downloadTrainingReport(trainingProgramChildRecordListDTO,trainingReportDTO,3,ShiroUtils.getLoginName());
        return AjaxResult.success(url);
    }


}